<?php
namespace app\service\system;

use app\model\system\MemberModel;
use app\model\system\MemberRoleModel;
use app\model\system\MenuModel;
use app\model\system\RoleModel;
use app\service\system\ManagerService;
use app\validate\system\MemberValidate;
use app\common\service\CaptchaService;
use app\common\service\JwtService;
use app\validate\system\LoginValidate;
use app\common\utils\Massage;
use app\common\utils\Res;
use app\apiadmin\service\TCSS\TImService;
use think\facade\Db;

class MemberService
{

    public static function login($param)
    {
        try {
            $validate = new LoginValidate();
            if (!$validate->scene('api')->check($param)) {
                return Res::error($validate->getError());
            }
            $result = MemberModel::findByUserName($param['user_name']);
            if (empty($result)) {
                return Res::error(Massage::USERNULL);
            }
            $result = $result->toArray();
            if (md5($param['password']) != $result['password']) {
                return Res::error(Massage::PASSWORDERROR);
            }
            if ($result['status'] != 1) {
                return Res::error(Massage::USERSTATUS);
            }
            if (!app()->make(CaptchaService::class)->check($param['code'])) {
                return Res::error(Massage::CAPTCHAERROR);
            }
            $result['roleId'] = MemberRoleModel::memberRole($result['uid']) ?? 0;
            $token = JwtService::createToken($result);
            return Res::ok($token);
        } catch (\PDOException $e) {
            return Res::error($e->getMessage());
        }

    }

    /**
     * @param $uid
     * @param $userName
     * @param $face
     * @param $nickName
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 查询用户信息
     */

    public static function memberInfo($uid,$userName,$face, $nickName,$phone){
        try {
            $roleList = MemberRoleModel::findByMemberRole($uid);
            $roleList = $roleList?$roleList->toArray():[];
            $roleName = '';
            if(!empty($roleList)){
                // 取第一个角色名
                $where['role_id'] = $roleList[0]['role_id'];
                $roleModel = new RoleModel();
                $roleName = $roleModel->where($where)->value('role_name');
            }
            $roleIds=[];
            foreach ($roleList as $k=>$v){

                $roleIds[]=$v['role_id'];
            }
            if (in_array(1, $roleIds)) {
                $result[0] = ['perms' => '*'];
            } else {
                $result = MenuModel::findPermsByUserName($uid);
            }
            $node = [];
            foreach ($result as $k => $v) {
                if ($v['perms']) {
                    array_push($node, $v['perms']);
                }
            }
            $data['perms']=$node;
            $data['userInfo']=['uid'=>$uid,'username'=>$userName,'face'=>$face, 'roleName'=>$roleName, 'nickName'=>$nickName,'phone'=>$phone];

            return  Res::ok($data);
        }catch (\PDOException $e){
            return  Res::error($e->getMessage());
        }
    }

    public static function memberDesc($uid)
    {
        try {
            $result = MemberModel::findByUid($uid);
            return Res::ok($result);
        } catch (\PDOException $e) {
            return Res::error($e->getMessage());
        }
    }

    public static function list($param)
    {
        $limit = (int) $param['pageSize'];
        $offset = ($param['pageNumber'] - 1) * $limit;
        $keyword = $param['keyword'];
        $map = [];
        if ($keyword) {
            $map[] = ['user_name|phone', 'like', '%' . $keyword . '%'];
        }
        $result = MemberModel::pageMap($map, $offset, $limit);
        $total = MemberModel::pageMapCount($map);
        $data = [
            'list' => $result,
            'total' => $total,
        ];
        return Res::ok($data);
    }

    public static function add($param)
    {
        try {
            $validate = new MemberValidate();
            if (!$validate->check($param)) {
                return Res::error($validate->getError());
            }

            //账号添加
            $uid = MemberModel::add($param);
            foreach ($param['role'] as $k => $v) {
                $data = [
                    'role_id' => $v,
                    'uid' => $uid,
                ];
                MemberRoleModel::add($data);
            }
            //同步小雪花账号
            ManagerService::add_manager($param);
            //同步im账号
            $ts = new TImService();
            $userIds=['M_'.$uid,'A_'.$uid];
            foreach($userIds as $userId){
                $ts->account_import_one($userId, $param['nick_name'], $param['face']);
            }
            return  Res::ok();
        }catch (\PDOException $e){
            return Res::error($e->getMessage());
        }
    }

    public static function edit($param)
    {
        try {
            //修改用户不需要验证用户的唯一性，所以注释掉，请勿打开验证规则
            $validate = new MemberValidate();
            if (!$validate->scene('edit')->check($param)) {
                return Res::error($validate->getError());
            }

            $reslut = MemberModel::findByUid($param['uid']);
            if ($param['password'] != $reslut['password']) {
                $param['password'] = md5($param['password']);
            }
            MemberModel::edit($param);

            //同步im账号
            $ts = new TImService();
            $userIds=['M_'.$param['uid'],'A_'.$param['uid']];
            foreach($userIds as $userId){
                $ts->account_import_one($userId, $param['nick_name'], $param['face']);
            }
//            MemberRoleModel::delByUid($param['uid']);
//            foreach ($param['role'] as $k => $v) {
//                $data = [
//                    'role_id' => $v,
//                    'uid' => $param['uid'],
//                ];
//                MemberRoleModel::add($data);
//            }
            return Res::ok();
        } catch (\PDOException $e) {
            return Res::error($e->getMessage());
        }
    }

    public static function del($id)
    {
        try {
            if ($id == 1) {
                return Res::error("系统默认超级管理员不允许删除");
            }
            MemberModel::del($id);
            MemberRoleModel::delByUid($id);
            return Res::ok();
        } catch (\PDOException $e) {
            return Res::error($e->getMessage());
        }
    }
}
